package com.novel.resources.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import cn.xuyanwu.spring.file.storage.FileInfo;
import cn.xuyanwu.spring.file.storage.recorder.FileRecorder;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.novel.resources.domain.SysFileDetail;
import com.novel.resources.mapper.SysFileDetailMapper;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

/**
 * 文件存储记录器
 *
 * @author novel
 * @since 2023/8/16 19:04
 */
@Service
@AllArgsConstructor
public class FileRecorderImpl implements FileRecorder {

    private final SysFileDetailMapper sysFileDetailMapper;

    /**
     * 保存文件信息到数据库
     */
    @SneakyThrows
    @Override
    public boolean save(FileInfo info) {
        SysFileDetail detail = BeanUtil.copyProperties(info, SysFileDetail.class, "attr");

        //这是手动获 取附加属性字典 并转成 json 字符串，方便存储在数据库中
        if (info.getAttr() != null) {
            detail.setAttr(new ObjectMapper().writeValueAsString(info.getAttr()));
        }
        int res = sysFileDetailMapper.insertSysFileDetail(detail);
        if (res > 0) {
            info.setId(detail.getId());
        }
        return res > 0;
    }

    /**
     * 根据 url 查询文件信息
     */
    @SneakyThrows
    @Override
    public FileInfo getByUrl(String url) {
        var sysFileDetail = new SysFileDetail();
        sysFileDetail.setUrl(url);
        var fileDetail = sysFileDetailMapper.selectSysFileDetail(sysFileDetail);

        FileInfo info = BeanUtil.copyProperties(fileDetail, FileInfo.class, "attr");

        //这是手动获取数据库中的 json 字符串 并转成 附加属性字典，方便使用
        if (StrUtil.isNotBlank(fileDetail.getAttr())) {
            info.setAttr(new ObjectMapper().readValue(fileDetail.getAttr(), Dict.class));
        }
        info.setBasePath("");
        return info;
    }

    /**
     * 根据 url 删除文件信息
     */
    @Override
    public boolean delete(String url) {
        var sysFileDetail = new SysFileDetail();
        sysFileDetail.setUrl(url);
        return sysFileDetailMapper.deleteSysFileDetail(sysFileDetail) > 0;
    }
}
